import { getUserInfo } from "@/api/login";
import Cookies from 'js-cookie';
import de from "element-ui/src/locale/lang/de";
import router from "@/router";
import store from "@/store";
import tree from "element-ui/packages/table/src/store/tree";
import { checkChildrenNode } from '@/store/support';
import http from '@/http';

const state = {
    phone: '', //用户登录的手机号
    userAuth: [], //全部路由
    hasUserAuth: false,
    userRole: '',
    sidebar: {
        opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
        withoutAnimation: false
    },
};

const mutations = {
    //设置手机号
    SET_USER_PHONE (state, phone) {
        state.phone = phone;
    },
    //设置权限列表
    SET_USER_AUTH (state, userAuth) {
        state.userAuth = userAuth;
    },
    //设置是否已经配置用户权限标志
    SET_HAS_USER_AUTH (state, hasUserAuth) {
        state.hasUserAuth = hasUserAuth;
    },
    //设置是否已经配置用户权限标志
    SET_USER_ROLE (state, userRole) {
        state.userRole = userRole;
    },
    //设置侧边栏收缩状态
    SET_TOGGLE_SIDEBAR: state => {
        state.sidebar.opened = !state.sidebar.opened;
        state.sidebar.withoutAnimation = false;
        if (state.sidebar.opened) {
            Cookies.set('sidebarStatus', 1);
        } else {
            Cookies.set('sidebarStatus', 0);
        }
    },
};

const actions = {
    GET_USER_INFO ({commit, dispatch}, token) {
        return new Promise((resolve, reject) => {
            getUserInfo({token : token}).then(res => {
                if (res.status === 200) {
                    res = res.body;
                    if (!store.state.user.hasUserAuth) {
                        router.options.routes.map(item => {
                            if (!item.meta.hidden) {
                                checkChildrenNode(item, res.module, res.role.split(","));
                            }
                            return item;
                        });
                        commit('SET_USER_AUTH', router.options.routes);
                        commit('SET_HAS_USER_AUTH', true);
                    }
                    commit('SET_USER_ROLE', res.role);
                    commit('SET_USER_PHONE', res.phone);
                    resolve(res);
                }
            })
        })
    },
    toggleSideBar({ commit }) {
        commit('SET_TOGGLE_SIDEBAR')
    },
};

export default {
    // namespaced: true,
    state,
    mutations,
    actions
}
